package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.service.*;
import com.itheima.dao.OrdersDao;
import com.itheima.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    //添加订单
    @Override
    public boolean add(Orders orders) {

        //0. 根据用户id，查询出来用户对象
        User user = userService.getById(BaseContext.getCurrentId());

        // 根据地址id，查询地址对象
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //1. 先往订单表添加数据
        //1.1 补充数据：
        //1.2 设置number::编号
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-" , ""));
        //1.3 设置status:: 默认值是1 表示等待付款，2等待派送，3已经派送，4.订单完成，5，订单取消
        orders.setStatus(2);
        //1.4 设置user_id
        orders.setUserId(BaseContext.getCurrentId());
        //1.5 设置address_book_id:: 不用赋值，页面提供了
        //1.6 设置order_time
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7 设置pay_method::不用赋值，页面提供了
        //1.8 设置amount::不用赋值，页面提供了
        //1.9 设置remark::不用赋值，页面提供了
        //1.10 设置phone
        orders.setPhone(addressBook.getPhone());
        //1.11 设置address
        String address =  ( addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "" ) +
                          ( addressBook.getCityName() != null ? addressBook.getCityName() : "" ) +
                         ( addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "" ) +
                         ( addressBook.getDetail() != null ? addressBook.getDetail() : "" );

        orders.setAddress(address);
        //1.12 设置user_name
        orders.setUserName(user.getName());
        //1.13 设置consignee
        orders.setConsignee(addressBook.getConsignee());

        //1.14 添加到订单表
        boolean result1 = save(orders);

        //2. 再往订单详情表添加数据

        //2.1 先把购物车的数据，先查询出来
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId , BaseContext.getCurrentId());
        List<ShoppingCart> cartList = shoppingCartService.list(lqw);

        List<OrderDetail> detailList = cartList.stream().map(shoppingCart -> {
            //一个购物车对象，映射成一个订单详情对象
            OrderDetail orderDetail = new OrderDetail();

            //拷贝数据
            BeanUtils.copyProperties(shoppingCart, orderDetail , "id");


            //设置订单详情，属于哪一个订单。
            orderDetail.setOrderId(orders.getId());

            return orderDetail;

        }).collect(Collectors.toList());

        //批量添加订单详情即可
        boolean result2 = orderDetailService.saveBatch(detailList);

        if(result1 && result2){
            //当已经添加好了订单，就需要把购物车的数据给清空了：：必须要做。
            shoppingCartService.remove(lqw);
            return true;
        }
        return false;
    }
}
